package me.itxuye.moment.base;

import android.os.Build;
import android.os.Bundle;
import android.support.annotation.IdRes;
import android.support.design.widget.AppBarLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.animation.DecelerateInterpolator;
import butterknife.ButterKnife;
import me.itxuye.moment.R;

/**
 * Author  : itxuye(itxuye@gmail.com)|(http://itxuye.com)
 * Date    : 2015-12-01
 * Time    : 20:34
 * FIXME
 */
public abstract class BaseToolBarActivity extends AppCompatActivity
    implements View.OnClickListener {

  protected AppBarLayout mAppBar;
  protected Toolbar mToolbar;
  protected boolean mIsHidden = false;

  @Override protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(provideContentViewId());

    ButterKnife.bind(this);

    mAppBar = findById(R.id.app_bar_layout);
    mToolbar = findById(R.id.toolbar);

    initView();

    initData();

    setListener();

    ////判断是否有toolbar
    if (mToolbar == null || mAppBar == null) {
      throw new IllegalStateException("No toolbar");
    }

    //toolbar相关的点击事件
    mToolbar.setOnClickListener(new View.OnClickListener() {
      @Override public void onClick(View v) {
        onToolbarClick();
      }
    });

    setSupportActionBar(mToolbar);

    if (canBack()) {
      ActionBar actionBar = getSupportActionBar();
      if (actionBar != null) actionBar.setDisplayHomeAsUpEnabled(true);
    }

    if (Build.VERSION.SDK_INT >= 21) {
      mAppBar.setElevation(10.6f);
    }
  }

  /*
     提供布局ID
  */
  abstract protected int provideContentViewId();

  /*
    toolbar相关点击事件
   */
  public void onToolbarClick() {
  }

  /*
     * 初始化控件调用的方法，建议使用
     * 查找View
     *
     * @param id   控件的id
     * @param <T> View类型
     * @return
   */
  public <T extends View> T findById(@IdRes int id) {
    return (T) findViewById(id);
  }

  //是否可以从当前页面退出
  public boolean canBack() {
    return false;
  }

  //向上滚动是否隐藏toolbar
  protected void hideOrShowToolbar() {
    mAppBar.animate()
        .translationY(mIsHidden ? 0 : -mAppBar.getHeight())
        .setInterpolator(new DecelerateInterpolator(2))
        .start();

    mIsHidden = !mIsHidden;
  }

  //初始化view
  protected abstract void initView();

  //设置监听
  protected abstract void setListener();

  //初始化data
  protected abstract void initData();

  protected abstract void getIntentData(Bundle saveInstance);
}
